<?php

namespace app\middleware;

use app\enum\UserCode;
use Tinywan\Jwt\JwtToken;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;

class AuthCheck implements MiddlewareInterface
{
    public function process(Request $request, callable $next): Response
    {
        $controller = $request->controller;
        $action = $request->action;
        // 反射控制器类，获取白名单
        try {
            $ref = new \ReflectionClass($controller);
            $noNeedLogin = $ref->getDefaultProperties()['noNeedLogin'] ?? [];
        } catch (\ReflectionException $e) {
            $noNeedLogin = [];
        }

        // 需要登录验证
        if (!in_array($action, $noNeedLogin)) {

            try {
                $userId = JwtToken::getCurrentId();
                $getTokenExp = JwtToken::getTokenExp();
                if ($getTokenExp <= 0) {
                    //token过期
                    return new Response(401, ['Content-Type' => 'application/json'], json_encode(['code' => 401, '登录过期'], JSON_UNESCAPED_UNICODE));
                }
                if (!$userId) {
                    return new Response(401, ['Content-Type' => 'application/json'], json_encode(['code' => 401, '请先登录'], JSON_UNESCAPED_UNICODE));
                }
                $user = JwtToken::getUser();
                if (!$user) {
                    return new Response(401, ['Content-Type' => 'application/json'], json_encode(['code' => 401, '未找到玩家'], JSON_UNESCAPED_UNICODE));
                }
                if ($user->status == UserCode::STATUS_DISABLE) {
                    return new Response(401, ['Content-Type' => 'application/json'], json_encode(['code' => 401, '账号已被禁用'], JSON_UNESCAPED_UNICODE));
                }
            } catch (\Tinywan\Jwt\Exception\JwtTokenException $e) {
                $data = ['code' => 401, 'msg' => $e->getMessage()];
                return new Response(401, ['Content-Type' => 'application/json'], json_encode($data, JSON_UNESCAPED_UNICODE));
            }

        }

        return $next($request);
    }
}
